import sys
import termios
import tty


def noblock_get_char():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    # 实时获取单个字符
    tty.setraw(fd)
    try:
        while True:
            cmd = sys.stdin.read(1)
            if cmd == "q" or ord(cmd) == 27:
                break
            print("-->", cmd)
    except Exception as e:
        print(e)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return cmd


if __name__ == "__main__":
    help_str = """
    实时获取单个字符
    按下 q 或 Esc 退出
    """
    print(help_str)
    noblock_get_char()
